package com.xhkj.componet;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ResourceUtils;

import com.aliyun.odps.Odps;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.PartitionSpec;
import com.aliyun.odps.Table;
import com.aliyun.odps.account.Account;
import com.aliyun.odps.account.AliyunAccount;
import com.aliyun.odps.tunnel.TableTunnel;
import com.xhkj.dao.MyFaceLibRecogDataDao;
import com.xhkj.dao.MyVehicleNoPassDataDao;
import com.xhkj.dao.XlsFaceDao;
import com.xhkj.dao.XlsVehicleDao;
import com.xhkj.model.Camera;
import com.xhkj.model.MyFaceLibRecogData;
import com.xhkj.model.MyVehicleNoPassData;
import com.xhkj.model.XlsFace;
import com.xhkj.model.XlsVehicle;
import com.xhkj.odps.UploadFaceThread;
import com.xhkj.odps.UploadVehicleThread;
import com.xhkj.util.DateUtil;

import jxl.Sheet;
import jxl.Workbook;
import lombok.extern.slf4j.Slf4j;

@Configuration // 1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@Slf4j
public class SaticScheduleTask {
	public static Map<String, Camera> faceCameraMap = new HashMap<String, Camera>();
	public static Map<String, Camera> vehicleCameraMap = new HashMap<String, Camera>();
	
	private static String accessId = "WB5ePNSftUOLzPoZ";
	private static String accessKey = "hUezl1X21Y7o6b6t9NK4VGz5FFzXAc";
	private static String odpsUrl = "http://service.cn-hs-hsgay-d01.odps.ops.hsgay/api";
	private static String tunnelUrl = "http://dt.cn-hs-hsgay-d01.odps.ops.hsgay";
	private static String project = "hengshuigongan";
	private static String table = "std_hkws_face";
	private static String table2 = "std_hkws_vehicle";
	private static String partition = "dt";
	@Autowired
	private MyFaceLibRecogDataDao fdao;
	@Autowired
	private MyVehicleNoPassDataDao vdao;
	@Autowired
	private XlsFaceDao xfdao;
	@Autowired
	private XlsVehicleDao xvdao;

	/**
	 * 加载摄像头数据
	 */
	@PostConstruct
	private void loadCameraData() {
		List<XlsFace> findAll = xfdao.findAll();
		for(XlsFace xf:findAll) {
			Camera c = new Camera();
			c.setLongitude(xf.getLongitude());
			c.setLatitude(xf.getLatitude());
			c.setName(xf.getName());
			faceCameraMap.put(xf.getCameraIndexCode(), c);
		}
		List<XlsVehicle> findAll2 = xvdao.findAll();
		for(XlsVehicle xv:findAll2) {
			Camera c2 = new Camera();
			c2.setLongitude(xv.getLongitude());
			c2.setLatitude(xv.getLatitude());
			c2.setName(xv.getName());
			vehicleCameraMap.put(xv.getCameraIndexCode(), c2);
		}
//		CameraCache.init();
//		try {
//			File file = ResourceUtils.getFile("classpath:faceCamera.xls");
//			Workbook wb = Workbook.getWorkbook(file); // 从文件流中获取Excel工作区对象（WorkBook）
//			Sheet sheet = wb.getSheet(0); // 从工作区中取得页（Sheet）
//			for (int i = 1; i < sheet.getRows(); i++) { // 循环打印Excel表中的内容
//				XlsFace xf = new XlsFace();
//				xf.setCameraIndexCode(sheet.getCell(0, i).getContents());
//				xf.setLongitude(sheet.getCell(1, i).getContents());
//				xf.setLatitude(sheet.getCell(2, i).getContents());
//				xf.setName(sheet.getCell(3, i).getContents());
//				xfdao.save(xf);
//			}
//		} catch (Exception e) {
//			log.error("cameracache load faceCamera.xls faild",e);
//			e.printStackTrace();
//		}
//		try {
//			File file2 = ResourceUtils.getFile("classpath:vehicleCamera.xls");
//			Workbook wb2 = Workbook.getWorkbook(file2); // 从文件流中获取Excel工作区对象（WorkBook）
//			Sheet sheet2 = wb2.getSheet(0); // 从工作区中取得页（Sheet）
//			for (int i = 1; i < sheet2.getRows(); i++) { // 循环打印Excel表中的内容
//				XlsVehicle xv = new XlsVehicle();
//				xv.setCameraIndexCode(sheet2.getCell(0, i).getContents());
//				xv.setLongitude(sheet2.getCell(1, i).getContents());
//				xv.setLatitude(sheet2.getCell(2, i).getContents());
//				xv.setName(sheet2.getCell(3, i).getContents());
//				xvdao.save(xv);
//			}
//		} catch (Exception e) {
//			log.error("cameracache load vehicleCamera.xls faild",e);
//			e.printStackTrace();
//		}
	}

	/**
	 * 获取数据库未上传人脸数据
	 */
//	@PostConstruct
//	//执行完后过10分钟继续执行下一次
//	@Scheduled(fixedRate = 600000)
	private void getFaceData() {
		int countState = fdao.getCountState(0);
		if (countState > 150000) {
			List<MyFaceLibRecogData> listByState = fdao.getListByState(0);
			UploadFaceThread ut = new UploadFaceThread(listByState);
			ut.start();
			for(MyFaceLibRecogData md:listByState) {
				md.setMyState(1);
			}
			fdao.saveAll(listByState);
		}
	}

	/**
	 * 获取数据库未上传车辆数据
	 */
	@PostConstruct
	//执行完后过10分钟继续执行下一次
	@Scheduled(fixedRate = 600000)
	// 每一个小时执行一次
//	@Scheduled(cron = "0 0 * * * ?")
	private void getVehicleData() {
		int countState = vdao.getCountState(0);
		if (countState > 150000) {
			List<MyVehicleNoPassData> listByState = vdao.getListByState(0);
			
			UploadVehicleThread ut = new UploadVehicleThread(listByState);
			ut.start();
			
			for(MyVehicleNoPassData md:listByState) {
				md.setMyState(1);
			}
			vdao.saveAll(listByState);
		}
	}
	/**
	 * 删除过期数据
	 */
	// 3.添加定时任务 每天23点执行
//	@Scheduled(cron = "0 0 23 * * ?")
	private void deleteData() {
		fdao.deleteByState(1);
		vdao.deleteByState(1);
	}

	// 项目启动时执行一次
//	@PostConstruct
//	// 3.添加定时任务 每天23点执行
//	@Scheduled(cron = "0 0 23 * * ?")
	//每隔1分钟
//	@Scheduled(cron = "0 */1 * * * ?")
	//每隔10秒
//	@Scheduled(cron = "*/5 * * * * ?")
	private void configureTasks() {
//		Calendar calendar = Calendar.getInstance();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//		Date date = calendar.getTime();
//		calendar.add(Calendar.DAY_OF_YEAR, num++);
//		Date date1 = calendar.getTime();
//		System.out.println(sdf.format(date));
//		String now = sdf.format(date);
//		String tommorw = sdf.format(date1);
		
		String now = DateUtil.getToday(new Date());
		String tommorw = DateUtil.getTommorrow(new Date());
		
		Account account = new AliyunAccount(accessId, accessKey);
		Odps odps = new Odps(account);
		odps.setEndpoint(odpsUrl);
		odps.setDefaultProject(project);

		TableTunnel tunnel = new TableTunnel(odps);
		// 设置tunnelUrl。
		tunnel.setEndpoint(tunnelUrl);

		PartitionSpec nowpt = new PartitionSpec();
		nowpt.set(partition, now);

		PartitionSpec tompt = new PartitionSpec();
		tompt.set(partition, tommorw);

		Table t_face = odps.tables().get(table);// 获取当前表
		Table t_car = odps.tables().get(table2);// 获取当前表
		try {
			boolean a = t_face.hasPartition(nowpt);
			if (!a) {
				t_face.createPartition(nowpt);
			}
			boolean a2 = t_face.hasPartition(tompt);
			if (!a2) {
				t_face.createPartition(tompt);
			}

			boolean b = t_car.hasPartition(nowpt);
			if (!b) {
				t_car.createPartition(nowpt);
			}
			boolean b2 = t_car.hasPartition(tompt);
			if (!b2) {
				t_car.createPartition(tompt);
			}
			log.info("create PartitionSpec -------------" + now + "   明天：" + tommorw);
		} catch (OdpsException e) {
			log.error("create patition error", e);
			e.printStackTrace();
		} 

	}

}